<template>
  <div class="header-with-back">
    <div class="back-nav" @click="goBack">
      <van-icon name="arrow-left" />
      <span style="font-size: 1.2rem">编辑个人信息</span>
    </div>
  </div>
  <div class="user-info-container">
    <div class="fw"/>
    <van-cell-group inset style="margin-bottom: 20px">
      <van-field
          v-model="editForm.userName"
          label="姓　　名"
          placeholder="请输入姓名"
          size="large"
          style="margin: 30px 0"
      />
      <van-field
          v-model="editForm.contact"
          label="联系方式"
          placeholder="请输入联系方式"
          size="large"
          style="margin: 30px 0"
      />
      <van-field
          v-model="editForm.email"
          label="邮　　箱"
          placeholder="请输入邮箱"
          size="large"
          style="margin: 30px 0"
      />
      <van-field
          v-model="editForm.department"
          label="学　　院"
          placeholder="请输入学院"
          size="large"
          style="margin: 30px 0"
      />
    </van-cell-group>

    <div class="button-container">
      <van-button
          :loading="loading"
          :disabled="isSubmitDisabled"
          type="primary"
          @click="handleSubmit"
      >保存修改</van-button>
    </div>
  </div>
</template>

<script setup lang="ts" name="UserInfoEditor">
import { ref, reactive, computed } from 'vue';
import router from "../../../Router";
import { useUserStore } from '../../../Store/modules/userinfo/UserInfo.js'
import { showDialog, showToast } from "vant";
import { updateUserUsingPost } from "../../../Api/yonghumokuai";

const userStore = useUserStore();

// 返回到个人中心
function goBack() {
  router.push('/cqust/userinfo');
}

// 编辑表单 - 只包含需要修改的字段
const editForm = reactive({
  userName: userStore.userInfo.userName || '',
  contact: userStore.userInfo.contact || '',
  email: userStore.userInfo.email || '',
  department: userStore.userInfo.department || ''
});

const loading = ref(false);

// 检查是否有修改
const hasChanges = computed(() => {
  const original = userStore.userInfo;
  return (
      editForm.userName !== original.userName ||
      editForm.contact !== (original.contact || '') ||
      editForm.email !== (original.email || '') ||
      editForm.department !== (original.department || '')
  );
});

// 提交按钮禁用状态
const isSubmitDisabled = computed(() => {
  return !hasChanges.value;
});

// 构建只包含修改过的字段的请求数据
function buildUpdateData() {
  const original = userStore.userInfo;
  const updateData: any = { userId: original.userId };

  if (editForm.userName !== original.userName) {
    updateData.userName = editForm.userName;
  }
  if (editForm.contact !== (original.contact || '')) {
    updateData.contact = editForm.contact || null;
  }
  if (editForm.email !== (original.email || '')) {
    updateData.email = editForm.email || null;
  }
  if (editForm.department !== (original.department || '')) {
    updateData.department = editForm.department || null;
  }

  return updateData;
}

// 提交修改
async function handleSubmit() {
  if (!hasChanges.value) {
    showToast('未修改任何信息');
    return;
  }
  if (editForm.contact.length != 11) {
    showToast("手机号码位数错误！")
    return
  }

  loading.value = true;
  try {
    const updateData = buildUpdateData();
    const response = await updateUserUsingPost(updateData);

    if (response.data.code === 0) {
      showToast('修改成功');
      // 更新本地存储的用户信息
      userStore.setUserInfo({
        ...userStore.userInfo,
        ...updateData
      });
      // 返回上一页
      goBack();
    } else {
      showToast(response.data.message || '修改失败');
    }
  } catch (error: any) {
    showDialog({
      message: error.response?.data?.message || '修改失败，请重试',
    });
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
/* 原有样式保持不变 */
.back-nav {
  position: fixed;
  left: 1%;
  top: 1.25%;
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  color: rgb(83, 30, 88);
  padding: 0.5rem;
  z-index: 10;
  font-size: 0.9rem;
}

.header-with-back .van-icon {
  position: static;
  font-size: 1.35rem;
}

.user-info-container {
  margin-top: 60px;
  padding: 20px;
  height: 100vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  background-color: white;
}

.fw {
  height: 7%;
}

.button-container {
  margin: 10px auto;
  width: 90%;
}

:deep(.van-button--primary) {
  width: 100%;
  background-color: #800080;
  border: none;
}

:deep(.van-button--primary:not(:disabled)) {
  background-color: #800080;
}

:deep(.van-button--primary:not(:disabled):hover) {
  background-color: #9a009a;
}

:deep(.van-button--primary:disabled) {
  background-color: rgba(128, 0, 128, 0.5);
  cursor: not-allowed;
}
</style>
